package com.project.les;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import com.project.les.view.adapters.StateListAdapter;
import com.project.les.view.elements.FeriadoViewElement;
import com.project.les.view.elements.StateViewElement;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

public class StateListActivity extends Activity {

	private List<StateViewElement> elementList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.states);

		List<FeriadoViewElement> data = DataHelper.getInstance().selectAll(
				"isState = 1", "state ASC, year, month, day");
		ExpandableListAdapter adapter = new StateListAdapter(this,
				this.getByStateElementList(data));

		ExpandableListView listView = (ExpandableListView) findViewById(R.id.listCadastro);
		listView.setAdapter(adapter);
	}

	/**
	 * Retorna uma lista de StateViewElement a partir de uma lista de
	 * FeriadoViewElement.
	 * 
	 * @param data
	 *            A lista de FeriadoViewElement
	 * @return Uma lista de StateViewElement equivalente à lista de entrada.
	 */
	private List<StateViewElement> getByStateElementList(
			List<FeriadoViewElement> data) {

		List<StateViewElement> stateList = new ArrayList<StateViewElement>();
		TreeMap<String, StateViewElement> stateMap = new TreeMap<String, StateViewElement>();

		Iterator<FeriadoViewElement> it = data.iterator();
		FeriadoViewElement nextElement;
		StateViewElement stateViewElement;
		while (it.hasNext()) {
			nextElement = it.next();
			if (!stateMap.containsKey(nextElement.getState())) {
				stateViewElement = new StateViewElement(nextElement.getState());
				stateMap.put(nextElement.getState(), stateViewElement);
			}

			stateMap.get(nextElement.getState()).addFeriado(nextElement);
		}

		Iterator<String> itMap = stateMap.keySet().iterator();
		while (itMap.hasNext())
			stateList.add(stateMap.get(itMap.next()));

		return stateList;
	}

}
